package com.guardchina.framework.web.model;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.*;

/**
 * 描述
 *
 * @author lwb
 * @since 2020/3/20
 */
public class RequestWrapper extends HttpServletRequestWrapper {

    private Map<String, String[]> params  = new HashMap<>();

    private Map<String, String> headers = new HashMap<>();

    public RequestWrapper(HttpServletRequest request) {
        super(request);
        this.params.putAll(request.getParameterMap());

        Enumeration<String > headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()){
            String name = headerNames.nextElement();
            String value = request.getHeader(name);
            headers.put(name, value);
        }
    }

    public void addParams(Map<String, Object> extraParams){
        for (Map.Entry<String, Object> entry : extraParams.entrySet()) {
            addParam(entry.getKey(), entry.getValue());
        }
    }

    public void addParam(String name, Object value){
        if(value == null){
            params.put(name, new String[]{});
        }else if (value instanceof String[]) {
            params.put(name, (String[]) value);
        } else if (value instanceof String) {
            params.put(name, new String[]{(String) value});
        } else {
            params.put(name, new String[]{String.valueOf(value)});
        }
    }

    public void addHeader(String name, String value){
        this.headers.put(name, value);
    }

    @Override
    public String getParameter(String name) {
        String[]values = params.get(name);
        if(values == null || values.length == 0) {
            return null;
        }
        return values[0];
    }
    @Override
    public Enumeration<String> getParameterNames() {
        Vector<String> v = new Vector<>();
        Set<Map.Entry<String, String[]>> entrySet = params.entrySet();
        for (Map.Entry<String, String[]> entry : entrySet) {
            v.add(entry.getKey());
        }

        return v.elements();
    }

    @Override
    public String[] getParameterValues(String name) {
        return params.get(name);
    }


    @Override
    public String getHeader(String name){
        return headers.get(name);
    }

    @Override
    public Enumeration<String> getHeaderNames() {
        return Collections.enumeration(headers.keySet());
    }

}
